package com.hujf.netty.chatModel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author Hujf
 * @title: GroupChatClient
 * @date 2021/2/2 0002下午 5:14
 * @description: TODO
 */
public class GroupChatClient {
    private final String host;
    private final int port;

    public GroupChatClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run(){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap client = new Bootstrap();
        try {


            //相关参数设置
            client.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline =socketChannel.pipeline();
                            channelPipeline.addLast("decoder",new StringDecoder());
                            channelPipeline.addLast("encoder",new StringEncoder());
                            channelPipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture cf = client.connect(host, port).sync();
            Channel channel = cf.channel();
            System.out.println("客户端启动 "+channel.localAddress());
            //客户端需要输入信息 需要创建扫描器
            Scanner s = new Scanner(System.in);
            while(s.hasNext()){
                String msg = s.nextLine();
                channel.writeAndFlush(msg+"\r\n");
            }

            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1",8989).run();
    }
}
